package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import classes.Artikal;
import classes.Stavka;

public class StavkaDAO {
	@SuppressWarnings("unused")
	private final Connection c;
	private final PreparedStatement qSelect, qInsert, qSelectAll, qDelete;
	
	public StavkaDAO(Connection c) throws Exception {
		this.c = c;
		
		qInsert= c.prepareStatement("INSERT INTO stavka(kolicina, Narudzbenica_idNarudzbenica, Artikal_idArtikal) VALUES(null, ?,?,?)");
		qSelect= c.prepareStatement("SELECT kolicina FROM stavka WHERE  idStavka= ?");
		qSelectAll = c.prepareStatement("SELECT * FROM stavka");
		qDelete = c.prepareStatement("DELETE FROM stavka WHERE idStavka=?");
	}

	public int insertStavka(Stavka s) throws Exception {
		if (s==null)
			throw new Exception("Nije moguce dodati nepostojecu stavku!");
        
		qInsert.setFloat(1, s.getKolicina());
		qInsert.setInt(2, s.getNarudzbenica().getIdNarudzbenica());
		qInsert.setInt(3, s.getArtikal().getIdArtikal());
		
		try{
			int rezultat= qInsert.executeUpdate();
			return rezultat;
		}
		catch(Exception ex){
			throw new Exception("Greska kod dodavanja artikla!");
		}
	}
	

	public List<Stavka> selectSveStavke() throws Exception{
		ResultSet rs = qSelectAll.executeQuery();
		List<Stavka> stavke = new ArrayList<Stavka>();
		while (rs.next()){
			Stavka s= new Stavka();
			
			s.setIdStavka(rs.getInt("idStavka"));
			s.setKolicina(rs.getFloat("kolicina"));
			s.setArtikal(DAOFactory.getArtikalDAO().selectArtikal(rs.getInt("Artikal_idArtikal")));
			s.setNarudzbenica(DAOFactory.getNarudzbenicaDAO().selectNarudzbenica(rs.getInt("Narudzbenica_idNarudzbenica")));
			stavke.add(s);
		}
		return stavke;
	}
	

	public Stavka selectStavka(int id) throws Exception {
		qSelect.setInt(1, id);
		ResultSet rs = qSelect.executeQuery();
		if (rs.next()==false)
			throw new Exception("Nema takvog artikla");
		while(rs.next()){
			Stavka s=new Stavka();
			s.setIdStavka(rs.getInt("idStavka"));
			s.setKolicina(rs.getFloat("kolicina"));
			s.setNarudzbenica(DAOFactory.getNarudzbenicaDAO().selectNarudzbenica(rs.getInt("Narudzbenica_idNarudzbenica")));
			s.setArtikal(DAOFactory.getArtikalDAO().selectArtikal(rs.getInt("Artikal_idArtikal")));
		}
		 return null;
	}
	public int deleteStavka(int id) throws Exception {
		qDelete.setInt(1, id);
		return qDelete.executeUpdate();
	}
}
